﻿var lsInfo = {
    current: 1,
    pageSize: allPageSize,
    data: [],
    totalRow: 0,
    totalPage: 0,
    oneDate: {},
    editState: false
};

// document.getElementById('nav').innerHTML = template('navs', navinfo2);

$('#nav li').eq(0).addClass('active');

var getList = function (obj) {
    $.ajax({
        cache: false,
        async: false,
        url: '/api/CommonApi?API=GetProjects',
        type: 'get',
        data: {
            ProjectName: searchObj.ProjectName,
            StartDate: searchObj.StartDate,
            EndDate: searchObj.EndDate,
            sorts: ' StartDate DESC',
            pagesize: obj.size,
            page: obj.index
        },
        dataType: 'json',
        success: function (data) {
            // console.log(data)
            if (data.Success) {
                obj.callback(data)
            }
        }
    });
};

getList({
    size: lsInfo.pageSize,
    index: lsInfo.current,
    callback: function (data) {
        // console.log(data)
        // console.log(JSON.stringify(data));
        var newData = data.ApiParamObj[0];
        for (var key in newData) {
            // console.log(newData[key])
            newData[key].StartDate = new Date(newData[key].StartDate).pattern('yyyy/MM/dd');
            newData[key].EndDate = new Date(newData[key].EndDate).pattern('yyyy/MM/dd');
            if (newData[key]['State'] === '????') {
                newData[key]['State'] = '';
            }
        }
        // 列表数据
        document.getElementById('listTable').innerHTML = template('l2List', newData);
        // 分页
        var pagesInfo = data.ApiParamObj[1];
        lsInfo.data = newData;
        lsInfo.totalRow = pagesInfo[0].totalRow;
        lsInfo.totalPage = pagesInfo[0].totalPage;

        $('#totalRow').html(lsInfo.totalRow);
        pagesSet(lsInfo);
        setPageSize(lsInfo);
        loading.hide();
    }
});

// 点击分页请求事件
var showPage = function (o) {
    // console.log(o)
    getList({
        size: o.pageSize,
        index: o.current,
        callback: function (data) {
            // console.log(data)
            // console.log(JSON.stringify(data));
            var newData = data.ApiParamObj[0];
            for (var key in newData) {
                newData[key].StartDate = new Date(newData[key].StartDate).pattern('yyyy/MM/dd');
                newData[key].EndDate = new Date(newData[key].EndDate).pattern('yyyy/MM/dd');
                if (newData[key]['State'] === '????') {
                    newData[key]['State'] = '';
                }
            }
            // 列表数据
            document.getElementById('listTable').innerHTML = template('l2List', newData);
            // 分页
            var pagesInfo = data.ApiParamObj[1];
            o.data = newData;
            o.totalRow = pagesInfo[0].totalRow;
            o.totalPage = pagesInfo[0].totalPage;

            $('#totalRow').html(o.totalRow);
            pagesSet(o);
            loading.hide();
        }
    });
};

// 新增弹框
$('#addProject').click(function () {
    /*
     PROJECT_STAGE = 项目阶段
     PROJECT_TYPE = 项目类型
     PROJECT_BRAND = 项目品牌
     */
    GetDictionarys('PROJECT_STAGE, PROJECT_TYPE, PROJECT_BRAND', function (data) {
        var arr = {};
        // console.log(JSON.stringify(data));
        var obj = {};
        var list = data.ApiParamObj;
        var i = 0;
        var l = list.length;

        for (; i < l; i++) {
            if (!obj[list[i].Key]) {
                obj[list[i].Key] = [];
                arr[list[i].Key] = list[i].Explain;
            }
            obj[list[i].Key].push(list[i]);
        }
        //console.log(arr)
        document.getElementById('td2').innerHTML = template('PROJECT_STAGE', obj);

        document.getElementById('td3').innerHTML = template('PROJECT_TYPE', obj);

        document.getElementById('td4').innerHTML = template('PROJECT_BRAND', obj);

        resetData($('#initProject form'));
    });
    lsInfo.editState = false;
    $('#projectTitle').html('新建项目');
    $('#save').html('新增');
    $('#initProject').modal('show');
});

// 编辑弹框
$('#table').on('click', '.editProject', function () {
    var index = $(this).parent().parent().index();
    lsInfo.oneDate = lsInfo.data[index];
    var v = lsInfo.oneDate;

    GetDictionarys('PROJECT_STAGE, PROJECT_TYPE, PROJECT_BRAND', function (data) {
        var arr = {};
        // console.log(JSON.stringify(data));
        var obj = {};
        var list = data.ApiParamObj;
        var i = 0;
        var l = list.length;

        for (; i < l; i++) {
            if (!obj[list[i].Key]) {
                obj[list[i].Key] = [];
                arr[list[i].Key] = list[i].Explain;
            }
            obj[list[i].Key].push(list[i]);
        }
        //console.log(arr)
        document.getElementById('td2').innerHTML = template('PROJECT_STAGE', obj);

        document.getElementById('td3').innerHTML = template('PROJECT_TYPE', obj);

        document.getElementById('td4').innerHTML = template('PROJECT_BRAND', obj);
        // console.log(JSON.stringify(v))

        setOptionSelected($('#td2'), v.ProjectStage);
        setOptionSelected($('#td3'), v.ProjectType);
        setOptionSelected($('#td4'), v.ProjectBrand);
    });

    lsInfo.editState = true;
    $('#td1').val(v.Name);
    $('#td5').val(new Date(v.StartDate).pattern('yyyy-MM-dd'));
    $('#td6').val(new Date(v.EndDate).pattern('yyyy-MM-dd'));

    $('#projectTitle').html('编辑项目');
    $('#save').html('修改');
    $('#initProject').modal('show');
});

// 提交
$('#table').on('click', '.submitProject', function () {
    var _this = $(this);
    var index = _this.parent().parent().index();
    lsInfo.oneDate = lsInfo.data[index];
    var v = lsInfo.oneDate;
    // console.log(JSON.stringify(v))
    loading.show();
    $.ajax({
        url: '/api/CommonApi?API=UpdateProjectState',
        type: 'post',
        data: {
            ApiParamObj: JSON.stringify({
                ID: v.ID,
                'State': 'SUBMIT'
            })
        },
        dataType: 'json',
        success: function (data) {
            if (data.Success) {
                console.log('submit success');
                _this.html('已提交').attr('disabled', 'disabled');
                showPage(lsInfo);
            }
        }
    });
});

// 删除
$('#table').on('click', '.delProject', function () {
    var index = $(this).parent().parent().index();
    lsInfo.oneDate = lsInfo.data[index];
    var v = lsInfo.oneDate;
    loading.show();
    // console.log(JSON.stringify(v))
    // 删除
    $.ajax({
        url: '/api/CommonApi?API=ProjectTableOp',
        type: 'post',
        data: {
            ApiParamObj: JSON.stringify({
                'ID': v.ID,
                'IsDelete': 1
            })
        },
        dataType: 'json',
        success: function (data) {
            if (data.Success) {
                console.log('del success');
                showPage(lsInfo);
                // loading.hide();
            }
        }
    });
});


function setOptionSelected(obj, t) {
    var o = $(obj)[0];
    var i = 0;
    var l = o.length;
    for (; i < l; i++) {
        if (o[i].innerHTML === t) {
            $(obj).children().eq(i).attr('selected', true);
            return;
        }
    }
}




// 新增或者修改项目
$('#save').click(function () {

    var form = $('#initProject form');
    var v1 = form[0].td1.value;
    var v2 = '';
    var v3 = '';
    var v4 = '';
    if (form[0].td2.selectedIndex !== -1) {
        v2 = form[0].td2[form[0].td2.selectedIndex].value;
    }

    if (form[0].td3.selectedIndex !== -1) {
        v3 = form[0].td3[form[0].td3.selectedIndex].value;
    }

    if (form[0].td4.selectedIndex !== -1) {
        v4 = form[0].td4[form[0].td4.selectedIndex].value;
    }

    var v5 = form[0].td5.value;
    var v6 = form[0].td6.value;

    var validator = new Validator();
    validator.add(v1, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目名称不能为空'
    }]);

    validator.add(v2, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目阶段不能为空'
    }]);

    validator.add(v3, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目类型不能为空'
    }]);

    validator.add(v4, [{
        strategy: 'isNonEmpty',
        errorMsg: '品牌不能为空'
    }]);

    validator.add(v5, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目开始时间不能为空'
    }]);

    validator.add(v6, [{
        strategy: 'isNonEmpty',
        errorMsg: '项目结束时间不能为空'
    }]);

    validator.add({
        start: v5,
        end: v6
    }, [{
        strategy: 'compareTime',
        errorMsg: '结束时间不能小于开始时间'
    }]);

    var errmsg = validator.start();
    if (errmsg) {
        alert(errmsg);
        return false;
    }

    // console.log(v1, v2, v3, v4, v5, v6)
    var submitData = {
        'Name': v1,
        'TypeID': v3,
        'BrandID': v4,
        'StageID': v2,
        'StartDate': v5,
        'EndDate': v6
    };
    var ajaxType = '';
    if (lsInfo.editState) {
        // 修改
        submitData.ID = lsInfo.oneDate.ID;
        ajaxType = 'post';
    } else {
        // 新增
        submitData.State = 'NO_SUBMIT';
        ajaxType = 'put';
    }
    // console.log(submitData, lsInfo.oneDate)
    var $this = $(this);
    $this.attr('disabled', 'disabled');
    $.ajax({
        url: '/api/CommonApi?API=ProjectTableOp',
        type: ajaxType,
        data: {
            ApiParamObj: JSON.stringify(submitData)
        },
        dataType: 'json',
        success: function (data) {
            if (data.Success) {
                console.log('success');
                $this.removeAttr('disabled');
                showPage(lsInfo);
                $('#initProject').modal('hide');
            }
        }
    });

});

function resetData(obj) {
    var o = obj[0];
    var i = 0;
    var l = o.length;
    for (; i < l; i++) {
        if (o[i].type === 'checkbox' || o[i].type === 'radio') {
            o[i].checked = false;
        } else if (o[i].type === 'select-one') {
            o[i][0].selected = true;
        } else if (o[i].type === 'button') {
        } else {
            o[i].value = '';
        }
    }
}
var nowDate = new Date().pattern('yyyy-MM-dd');
// $('.input-daterange input').datetimepicker({
// $('.input-daterange input').datepicker({
//   // bootcssVer: 3,
//   todayBtn: 'linked',
//   weekStart: 0,
//   autoclose: true,
//   // todayHighlight: 1,
//   startView: 0,
//   startDate: nowDate,
//   // startDate: '2016-06-15',
//   // endDate: '2016-06-16',
//   format: 'yyyy-mm-dd',
//   // forceParse: 1,
//   // showMeridian: 1,
//   language: 'zh-CN',
//   minView: 0
// });

$('.input-daterange input').datetimepicker({
    bootcssVer: 2,
    todayBtn: true,
    weekStart: 0,
    autoclose: 1,
    startView: 2,
    startDate: nowDate,
    format: 'yyyy-mm-dd',
    language: 'zh-CN',
    minView: 2
});